<template>
    <el-card v-loading="loading">
        <div slot="header" class="header-box">
            <span>商品信息编辑</span>
        </div>
        <el-form :model="form" label-width="10rem" :rules="rules" ref="form" size="small">
            <el-form-item label="请选择分类:" required style="width: 1000px">
                <el-select v-model="category1" @change="changeCategory1" style="width: 30%">
                    <el-option v-for="item in categories1" :key="item.id" :label="item.name"
                               :value="item.id"/>
                </el-select>
                <el-select v-model="category2" @change="changeCategory2" style="width: 30%">
                    <el-option v-for="item in categories2" :key="item.id" :label="item.name"
                               :value="item.id"/>
                </el-select>
                <el-select v-model="category3" @change="changeCategory3" style="width: 30%">
                    <el-option v-for="item in categories3" :key="item.id" :label="item.name"
                               :value="item.id"/>
                </el-select>
            </el-form-item>

            <el-form-item label="商品名称:" prop="name" style="min-width: 500px">
                <el-input type="text" v-model="form.name" placeholder="请输入商品名称"
                          maxlength="50" show-word-limit/>
            </el-form-item>

            <el-row style="min-width: 500px">
                <el-col :span="18">
                    <el-form-item label="商品简介:" prop="description" style="width: 100%">
                        <el-input type="textarea" v-model="form.description"
                                  class="goods-description"
                                  placeholder="请输入商品简介" maxlength="100" show-word-limit rows="5"/>

                    </el-form-item>
                </el-col>

                <el-col :span="6">
                    <el-form-item label="商品图片:" :error="goodsImageShowError?'商品图片不能为空':''">
                        <el-upload
                                class="goods-image"
                                action="btpj"
                                :http-request="uploadFile"
                                :show-file-list="false"
                                :before-upload="beforeImageUpload">
                            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" alt="商品图片">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row style="min-width: 800px">
                <el-col :span="8">
                    <el-form-item label="商品原始价格（元）:" prop="originalPrice" style="min-width: 250px">
                        <el-input type="number" min="0" @change="checkOriginalPrice" v-model="form.originalPrice"
                                  placeholder="请输入商品价格"/>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="商品实际售价（元）:" prop="sellingPrice" style="min-width: 250px">
                        <el-input type="number" min="0" @change="checkSellingPrice" v-model="form.sellingPrice"
                                  placeholder="请输入商品实际售价"/>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="商品库存数（件）:" prop="stockNum">
                        <el-input-number v-model="form.stockNum" placeholder="商品库存数" :min="1"/>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="商品关键词:" prop="keywords">
                <el-input v-model="form.keywords" style="min-width: 200px" placeholder="请输入商品小标签" maxlength="50"
                          show-word-limit/>
            </el-form-item>

            <el-form-item label="上架状态:">
                <el-radio v-model="form.sellStatus" label='0'>上架</el-radio>
                <el-radio v-model="form.sellStatus" label='1'>下架</el-radio>
            </el-form-item>

            <el-form-item :error="detailContentBlankShowError?'商品详情不能为空':''" style="min-width: 1000px">
                <mavon-editor placeholder="请输入商品详情" v-model="form.detailContent"/>
            </el-form-item>

            <el-form-item class="button-wrap">
                <el-button type="info">返回商品列表</el-button>
                <el-button type="primary" @click="saveGoods">保存商品</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script>
    import {getCategoryList} from "../api/categoryApi";
    import {addGoods} from "../api/goodsApi";
    import {uploadFile} from "../api/fileApi";

    export default {
        name: "GoodsInfo",
        data() {
            return {
                loading: false,
                categories1: [],
                categories2: [],
                categories3: [],
                category1: '',
                category2: '',
                category3: '',
                form: {
                    name: '',
                    description: '',
                    categoryId: '',
                    imageUrl: '',
                    originalPrice: '',
                    sellingPrice: '',
                    stockNum: '',
                    keywords: '',
                    sellStatus: '0',
                    detailContent: ''
                },
                rules: {
                    name: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
                    description: [{required: true, message: '请输入商品简介', trigger: 'blur'}],
                    originalPrice: [{required: true, message: '请输入商品原始价格(不能为负数)', trigger: 'blur'}],
                    sellingPrice: [{required: true, message: '请输入商品实际售价(不能为负数)', trigger: 'blur'},],
                    stockNum: [{required: true, message: '商品库存数不可为空', trigger: 'blur'},],
                    keywords: [{required: true, message: '请输入商品关键词', trigger: 'blur'}],
                },
                detailContentBlankShowError: false,
                goodsImageShowError: false,
            }
        },
        mounted() {
            this.getCategory();
        },
        methods: {
            getCategory() {
                getCategoryList().then(res => {
                    if (res.status === 0) {
                        if (res.data.list.length > 0) {
                            this.categories1 = res.data.list;
                            this.category1 = this.categories1[0].name;
                            this.form.categoryId = this.categories1[0].id;
                            this.changeCategory1(this.form.categoryId)
                        }
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            },
            changeCategory1(value) {
                this.category2 = '';
                this.category3 = '';
                this.categories2 = [];
                this.categories3 = [];
                getCategoryList(value).then(res => {
                    if (res.status === 0) {
                        if (res.data.list.length > 0) {
                            this.categories2 = res.data.list;
                            this.category2 = this.categories2[0].name;
                            this.form.categoryId = this.categories2[0].id;
                            this.changeCategory2(this.form.categoryId)
                        }
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            },
            changeCategory2(value) {
                this.category3 = '';
                this.categories3 = [];
                getCategoryList(value).then(res => {
                    if (res.status === 0) {
                        if (res.data.list.length > 0) {
                            this.categories3 = res.data.list;
                            this.category3 = this.categories3[0].name;
                            this.form.categoryId = this.categories3[0].id;
                        }
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            },
            changeCategory3(value) {
                this.form.categoryId = value;
            },
            checkOriginalPrice(value) {
                if (value < 0) {
                    this.form.originalPrice = '';
                }
            },
            checkSellingPrice(value) {
                if (value < 0) {
                    this.form.sellingPrice = '';
                }
            },
            beforeImageUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';
                const isLt10M = file.size / 1024 / 1024 < 10;
                if (!isJPG && !isPNG) {
                    this.$message.error('上传商品图片只能是 JPG/PNG 格式!');
                }
                if (!isLt10M) {
                    this.$message.error('上传商品图片大小不能超过 10MB!');
                }
                return (isJPG || isPNG) && isLt10M;
            },
            uploadFile(params) {
                uploadFile(params.file).then(res => {
                    console.log(res);
                    if (res.status === 0) {
                        this.form.imageUrl = res.data;
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            },
            saveGoods() {
                this.$refs['form'].validate(valid => {
                        this.detailContentBlankShowError = this.form.detailContent.trim().length === 0;
                        this.goodsImageShowError = this.form.imageUrl.trim().length === 0;
                        if (valid && !this.detailContentBlankShowError && !this.goodsImageShowError) {
                            this.loading = true;
                            addGoods(this.form.name, this.form.description, this.form.categoryId,
                                this.form.imageUrl, this.form.detailContent, this.form.originalPrice,
                                this.form.sellingPrice, this.form.stockNum, this.form.keywords,
                                this.form.sellStatus).then(res => {
                                this.loading = false;
                                if (res.status === 0) {
                                    this.$message.success(res.msg);
                                    this.$refs['form'].resetFields();
                                    this.form.detailContent = '';
                                    this.form.imageUrl = '';
                                } else {
                                    this.$message.error(res.msg);
                                }
                            })
                        }
                    }
                );
            },
        },
    }
</script>

<style scoped lang="stylus">
    .el-card {
        text-align left
        margin 10px
        border-top 3px solid cornflowerblue

        .header-box {
            span {
                font-size 1.3rem
            }
        }

        .el-form {
            .el-select {
                margin-right 10px
            }

            .goods-image {
                border: 1px dashed #d9d9d9;
                width 110px
                border-radius: 6px;
                cursor: pointer;

                .avatar-uploader-icon {
                    font-size: 28px;
                    color: #8c939d;
                    width: 110px;
                    height: 110px;
                    line-height: 110px;
                    text-align: center;
                }

                .avatar {
                    width: 110px
                    height: 110px
                    display: block
                }
            }

            .button-wrap {
                margin-top 20px
                display flex
                justify-content flex-end
            }
        }
    }

</style>
